<template>
  <XenListPage
    title="招聘中心"
    :dataList="recruitPublishList"
    :visibleFields="visibleFields"
    :filterFields="filterFields"
    :actions="actions"
    :themeConfig="themeConfig"
    :loading="loading"
    :enableAutoRefresh="false"
    :enableSilentRefresh="true"
    :silentRefreshFn="silentRefreshFn"
    searchPlaceholder="点击筛选招聘中心信息"
    emptyText="暂无招聘中心信息"
    emptyDesc="暂无数据"
    detailPagePath="/subpkg-hr-syshrrecruitpublishrequestbill/details"
    permission-module="syshrrecruitpublishrequestbill"
    :showAddButton="false"
    @filter="handleFilter"
    @refresh="handleRefresh"
    @silent-refresh="handleSilentRefresh"
    @action="handleCustomAction"
  >
    <!-- 自定义插槽图标 -->
    <template #search-icon>
      <uni-icons type="search" size="18" color="#999"></uni-icons>
    </template>
    <template #loading-icon>
      <uni-icons type="spinner-cycle" size="24" color="#666"></uni-icons>
    </template>
    <template #empty-icon>
      <uni-icons type="info" size="48" color="#ccc"></uni-icons>
    </template>
    <template #action-icon-view>
      <uni-icons type="eye" size="16" color="#7881de"></uni-icons>
    </template>
    <template #action-icon-apply>
      <uni-icons type="personadd" size="16" color="#67C23A"></uni-icons>
    </template>
  </XenListPage>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import XenListPage from "@/layouts/XenListPage.vue";
import SysHrRecruitPublishRequestBillApi from "./api/index";
import commonApi from "@/api/common";
import { processDateRangeField } from "@/utils/dateRangeUtils";
import { formatDateTime } from "@/utils/xenUtils";
import type {
  ISysHrRecruitPublishRequestBillView,
  ISysHrRecruitPublishRequestBillQuery,
} from "./api/interface";

// 创建API实例
const api = SysHrRecruitPublishRequestBillApi();
const commonApiInstance = commonApi();

// 主题配置
const themeConfig = {
  primaryColor: "#7881de",
  secondaryColor: "#764ba2",
  gradientStart: "#667eea",
  gradientEnd: "#764ba2",
};

// 定义列表显示字段
const visibleFields = [
  {
    key: "BillCode",
    label: "招聘发布单号",
    formatter: (value: any) => value || "",
  },
  {
    key: "Title",
    label: "招聘标题",
    formatter: (value: any) => value || "",
  },
  {
    key: "HireNumber",
    label: "招聘人数",
    formatter: (value: any) => value || "",
  },
  {
    key: "OrgName",
    label: "公司",
    formatter: (value: any) => value || "",
  },
  {
    key: "GroupName",
    label: "所属部门",
    formatter: (value: any) => value || "",
  },
  {
    key: "WorkflowStatus",
    label: "流程状态",
    type: "badge",
    formatter: (value: any) => value || "",
    badgeConfig: {
      colorMap: {
        待提交: "gray",
        提交中: "blue",
        审核中: "orange",
        已完成: "green",
        已取消: "red",
      },
      defaultColor: "gray",
      prefix: "badge-",
    },
  },
  {
    key: "BillStatus",
    label: "单据状态",
    formatter: (value: any) => value || "",
  },
  {
    key: "ExpectedDate",
    label: "到岗时间",
    formatter: (value: any) => {
      if (!value) return "";
      const formattedDateTime = formatDateTime(value);
      return formattedDateTime ? formattedDateTime.split(" ")[0] : "";
    },
  },
  {
    key: "PublishStartDate",
    label: "发布开始时间",
    formatter: (value: any) => {
      if (!value) return "";
      const formattedDateTime = formatDateTime(value);
      return formattedDateTime ? formattedDateTime.split(" ")[0] : "";
    },
  },
  {
    key: "PublishEndDate",
    label: "发布结束时间",
    formatter: (value: any) => {
      if (!value) return "";
      const formattedDateTime = formatDateTime(value);
      return formattedDateTime ? formattedDateTime.split(" ")[0] : "";
    },
  },
  {
    key: "Approver",
    label: "审批人",
    formatter: (value: any) => value || "",
  },
  {
    key: "ApprovalTime",
    label: "审批时间",
    formatter: (value: any) => {
      return formatDateTime(value);
    },
  },
  {
    key: "EducationRequirement",
    label: "学历要求",
    formatter: (value: any) => value || "",
  },
  {
    key: "SalaryRange",
    label: "薪资范围",
    formatter: (value: any) => value || "",
  },
  {
    key: "MajorRequirement",
    label: "专业要求",
    formatter: (value: any) => value || "",
  },
  {
    key: "ContactPerson",
    label: "联系人",
    formatter: (value: any) => value || "",
  },
  {
    key: "ContactPhone",
    label: "联系电话",
    formatter: (value: any) => value || "",
  },
  {
    key: "ContactEmail",
    label: "联系邮箱",
    formatter: (value: any) => value || "",
  },
  {
    key: "IsExternalPublish",
    label: "是否对外发布",
    formatter: (value: any) => (value ? "是" : "否"),
  },
  {
    key: "Description",
    label: "招聘描述",
    formatter: (value: any) => value || "",
  },
  {
    key: "JobRequirement",
    label: "岗位要求",
    formatter: (value: any) => value || "",
  },
  {
    key: "Benefits",
    label: "福利待遇",
    formatter: (value: any) => value || "",
  },
  {
    key: "GenderRequirement",
    label: "性别要求",
    formatter: (value: any) => value || "",
  },
  {
    key: "AgeRequirement",
    label: "年龄要求",
    formatter: (value: any) => value || "",
  },
  {
    key: "OtherRequirement",
    label: "其他要求",
    formatter: (value: any) => value || "",
  },
  {
    key: "Remark",
    label: "备注",
    formatter: (value: any) => value || "",
  },
];

// 定义搜索筛选字段
const filterFields: any[] = [
  {
    key: "title",
    label: "招聘标题",
    placeholder: "请输入招聘标题",
  },
  {
    key: "billCode",
    label: "单据编号",
    placeholder: "请输入单据编号",
  },
  {
    key: "workflowStatus",
    label: "流程状态",
    type: "selector",
    placeholder: "请选择流程状态",
    options: [
      "待提交",
      "提交中",
      "审核中",
      "已完成",
      "已取消",
      "待处理",
      "处理中",
      "已处理",
    ],
  },
  {
    key: "groupId",
    label: "所属部门",
    type: "department-picker",
    placeholder: "请选择所属部门",
    popupTitle: "选择部门",
    departmentData: [], // 将在页面加载时动态填充
  },
  {
    key: "isExternalPublish",
    label: "对外发布",
    type: "selector",
    placeholder: "请选择是否对外发布",
    options: ["是", "否"],
  },
  {
    key: "expectedDate",
    label: "到岗时间",
    type: "daterange",
    placeholder: "请选择到岗时间范围",
  },
  {
    key: "billStatus",
    label: "单据状态",
    type: "selector",
    placeholder: "请选择单据状态",
    options: ["草稿", "正文"],
  },
  {
    key: "remark",
    label: "备注",
    placeholder: "请输入备注",
  },
];

// 定义操作按钮
const actions = [
  {
    key: "view",
    label: "查看",
    icon: "eye",
    color: "#7881de",
    class: "view-btn",
  },
  {
    key: "apply",
    label: "应聘申请",
    icon: "personadd",
    color: "#67C23A",
    class: "apply-btn",
  },
];

// 招聘发布申请列表数据
const recruitPublishList = ref<ISysHrRecruitPublishRequestBillView[]>([]);

// 部门数据缓存（用于名称和ID的转换）
const departmentDataCache = ref<any[]>([]);

// 处理筛选
const handleFilter = async (filterParams: Record<string, any>) => {
  loading.value = true;
  try {
    // 构建查询参数，映射到API接口需要的字段
    const queryParams: ISysHrRecruitPublishRequestBillQuery = {
      Limit: 9999, // 一次性获取所有数据
      Page: 1,
    };

    // 根据筛选参数构建查询对象
    if (filterParams.title) {
      queryParams.Title = filterParams.title;
    }
    if (filterParams.billCode) {
      queryParams.BillCode = filterParams.billCode;
    }
    if (filterParams.workflowStatus) {
      queryParams.WorkflowStatus = filterParams.workflowStatus;
    }
    if (filterParams.groupId) {
      // XenDepartmentPicker组件直接返回部门ID
      queryParams.GroupId = filterParams.groupId;
    }
    if (filterParams.isExternalPublish) {
      queryParams.IsExternalPublish = filterParams.isExternalPublish === "是";
    }
    // 处理到岗时间范围：确保结束日期包含当天的所有时间
    const expectedDateRange = processDateRangeField(
      filterParams,
      "expectedDate",
    );
    if (expectedDateRange) {
      queryParams.ExpectedDate = expectedDateRange;
    }
    if (filterParams.billStatus) {
      queryParams.BillStatus = filterParams.billStatus;
    }
    if (filterParams.remark) {
      queryParams.Remark = filterParams.remark;
    }

    const response = await api.publicSearch(queryParams);

    if (response && response.Data) {
      recruitPublishList.value = response.Data;
    } else {
      recruitPublishList.value = [];
    }
  } catch (error) {
    recruitPublishList.value = [];

    // 显示错误提示
    uni.showToast({
      title: "筛选搜索失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 静默刷新数据获取函数（供XenListPage组件调用）
const silentRefreshFn = async () => {
  const response = await api.publicSearch({
    Limit: 9999, // 一次性获取所有数据
    Page: 1,
  });
  return response?.Data || [];
};

// 处理静默刷新结果
const handleSilentRefresh = (
  newData: ISysHrRecruitPublishRequestBillView[],
) => {
  recruitPublishList.value = newData;
};

// 处理刷新事件
const handleRefresh = () => {
  // 只有在首次加载或明确需要刷新时才调用fetchData
  if (recruitPublishList.value.length === 0) {
    fetchData();
  }
};

// 处理自定义操作
const handleCustomAction = ({
  actionKey,
  item,
}: {
  actionKey: string;
  item: any;
}) => {
  switch (actionKey) {
    case "apply":
      handleJobApplication(item);
      break;
    default:
      console.log("未知操作:", actionKey);
  }
};

// 处理应聘申请
const handleJobApplication = (recruitItem: any) => {
  const recruitId = recruitItem.ID || recruitItem.id;
  if (!recruitId) {
    uni.showToast({
      title: "招聘信息ID缺失",
      icon: "none",
      duration: 2000,
    });
    return;
  }

  // 跳转到应聘申请新增页，并传递招聘发布单ID
  uni.navigateTo({
    url: `/subpkg-hr-syshrinterviewrequestbill/create?recruitPublishId=${recruitId}&recruitTitle=${encodeURIComponent(
      recruitItem.Title || "招聘信息",
    )}&company=${encodeURIComponent(
      recruitItem.OrgName || "",
    )}&department=${encodeURIComponent(recruitItem.GroupName || "")}`,
    fail: (error) => {
      console.error("跳转失败:", error);
      uni.showToast({
        title: "跳转失败，请稍后重试",
        icon: "none",
        duration: 2000,
      });
    },
  });
};

// 加载状态
const loading = ref(false);

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await api.publicSearch({
      Limit: 9999, // 一次性获取所有数据
      Page: 1,
    });

    if (response && response.Data) {
      recruitPublishList.value = response.Data;
    } else {
      recruitPublishList.value = [];
    }
  } catch (error) {
    recruitPublishList.value = [];

    // 显示错误提示
    uni.showToast({
      title: "获取招聘中心信息失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 加载部门数据
const loadDepartmentData = async () => {
  try {
    const response = await commonApiInstance.GetParentsTree();
    if (response && Array.isArray(response)) {
      // 缓存部门数据
      departmentDataCache.value = response;

      // 找到部门筛选字段并更新其部门数据
      const departmentField = filterFields.find(
        (field) => field.key === "groupId",
      );
      if (departmentField) {
        departmentField.departmentData = response;
      }
    }
  } catch (error) {
    console.error("加载部门数据失败:", error);
  }
};

// 页面加载
onMounted(async () => {
  await loadDepartmentData();
  fetchData();
});
</script>

<style lang="scss" scoped>
// 自定义按钮样式
:deep(.action-btn.apply-btn) {
  color: #67c23a !important;
  background-color: rgba(103, 194, 58, 0.1) !important;
}
</style>
